﻿using System;
using System.Collections.Generic;
using System.IO;
using FlagLib.Extensions;

namespace FlagTunes.Core
{
    public class Library
    {
        private readonly ICollection<Playlist> playlists;
        private readonly Playlist mainPlaylist;

        /// <summary>
        /// Gets the playlists.
        /// </summary>
        /// <value>The playlists.</value>
        public IEnumerable<Playlist> Playlists
        {
            get { return this.playlists; }
        }

        /// <summary>
        /// Gets the main playlist.
        /// </summary>
        public Playlist MainPlaylist
        {
            get { return this.mainPlaylist; }
        }

        /// <summary>
        /// Occurs when a song has been added.
        /// </summary>
        public event EventHandler<SongEventArgs> SongAdded;

        /// <summary>
        /// Occurs when the creation has finished.
        /// </summary>
        public event EventHandler CreationFinished;

        /// <summary>
        /// Initializes a new instance of the <see cref="Library"/> class.
        /// </summary>
        public Library()
        {
            this.playlists = new List<Playlist>();

            this.mainPlaylist = new Playlist("Music");

            this.playlists.Add(this.mainPlaylist);
        }

        /// <summary>
        /// Searches all songs recursively in the specified directory and adds them to the library.
        /// </summary>
        /// <param name="directory">The directory to search.</param>
        public void AddSongsFromDirectory(DirectoryInfo directory)
        {
            var songCrawler = new SongFinder(directory.FullName);

            songCrawler.SongFound += (sender, e) =>
                {
                    this.MainPlaylist.Songs.Add(e.Song);
                    this.OnSongAdded(new SongEventArgs(e.Song));
                };

            songCrawler.Finished += (sender, e) => this.OnCreationFinished(e);

            songCrawler.StartAsync();
        }

        /// <summary>
        /// Raises the <see cref="SongAdded"/> event.
        /// </summary>
        /// <param name="e">The <see cref="FlagTunes.Core.SongEventArgs"/> instance containing the event data.</param>
        protected virtual void OnSongAdded(SongEventArgs e)
        {
            this.SongAdded.RaiseSafe(this, e);
        }

        protected virtual void OnCreationFinished(EventArgs e)
        {
            this.CreationFinished.RaiseSafe(this, e);
        }
    }
}